package com.lbn.jfqsc.app.account.info;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.lbn.baseframe.base.BaseActivity;
import com.lbn.baseframe.image.LoaderImage;
import com.lbn.baseframe.ui.NAppbar;
import com.lbn.baseframe.utils.EasyToast;
import com.lbn.baseframe.utils.L;
import com.lbn.baseframe.utils.SPUtils;
import com.lbn.jfqsc.App;
import com.lbn.jfqsc.R;
import com.lbn.jfqsc.business.bean.User;
import com.lbn.jfqsc.widget.PhotoDialog;
import com.lypeer.fcpermission.FcPermissions;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class InfoActivity extends BaseActivity<InfoPresenter> implements InfoView {

    @BindView(R.id.photo)
    ImageView photo;
    @BindView(R.id.user_name)
    EditText userName;
    @BindView(R.id.user_phone)
    TextView userPhone;
    @BindView(R.id.email)
    EditText email;
    private Uri imageUri;
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);
        ButterKnife.bind(this);
        setAppbar(new NAppbar(this));
        appbar.setTitle("个人信息");
        appbar.openBack();
    }


    @Override
    public void onPresenterCreated() {
        super.onPresenterCreated();
        userPhone.setText(App.getUser().getPhone());
        userName.setText(App.getUser().getName());
        email.setText(App.getUser().getEmail()==null?"":App.getUser().getEmail());
        if(App.getUser().getHead()!=null){
            LoaderImage.displayImage(App.getUser().getHead(),photo);
        }

    }

    public String getUserName() {
        return userName.getText().toString();
    }



    public String getEmail() {
        return email.getText().toString();
    }

    @Override
    public InfoPresenter createPresenter() {
        return new InfoPresenter();
    }


    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, InfoActivity.class));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 1:
                //相册
                CropImage.activity(data.getData())
                        .setAspectRatio(1, 1)
                        .setCropShape(CropImageView.CropShape.RECTANGLE)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setAllowCounterRotation(false)
                        .start(this);
                break;
            case 2:
                //照相机
                CropImage.activity(imageUri)
                        .setAspectRatio(1, 1)
                        .setCropShape(CropImageView.CropShape.RECTANGLE)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setAllowCounterRotation(false)
                        .start(this);
                break;
            case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE:
                //裁剪
                CropImage.ActivityResult result = CropImage.getActivityResult(data);
                Uri resultUri = result.getUri();
                file = new File(resultUri.getPath());
                setPhoto(resultUri);
                break;
        }
    }


    @NonNull
    @Override
    protected String getRationale4NeverAskAgain() {
        return "更换头像，请先打开相应权限";
    }

    @Override
    public void onPermissionDenied(int requestCode, List<String> perms) {
//        FcPermissions.checkDeniedPermissionsNeverAskAgain(this, perms);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (perms.size() < 3)
            return;
        imageUri = PhotoDialog.makeSelectPhoto(this);
    }

    private void requestCameraPermission() {
        FcPermissions.requestPermissions(this,
                "即将请求与相机和相册有关的权限，是否立即前往",
                FcPermissions.REQ_PER_CODE,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }


    private void setPhoto(Uri uri) {
        Glide.with(this)
                .load(uri)
                .fitCenter()
                .skipMemoryCache(false)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .dontAnimate()
                .into(photo);
    }


    @OnClick({R.id.photo, R.id.send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.photo:
                requestCameraPermission();
                break;
            case R.id.send:
                if (file != null) {
                    mPresenter.upToken(file,getUserName(),getEmail());
                    return;
                }
                mPresenter.upUserInfo(getUserName(),getEmail(),null);
                break;
        }

    }

    @Override
    public void onSucceed() {
        EasyToast.showShort(this, "修改成功");
        mPresenter.login();
    }

    @Override
    public void onSucceed(User user) {
        App.setUser(user);
        String userJson = new Gson().toJson(user);
        L.e("saveUser:" + userJson);
        SPUtils.put(this, "USER", userJson);
        finish();
    }
}
